package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.dao.DAOUtil;
import model.dao.IslandDAO;
import model.entity.Island;
import postgis.util.PostGISUtil;
import servlets.util.ParamUtil;
import util.JSONUtil;

import com.vividsolutions.jts.geom.Point;

import exceptions.ParameterNotFoundException;

@WebServlet("/GetIslands")
public class GetIslandsServlet extends HttpServlet {
	private static final long serialVersionUID = 7649116587706759224L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GetIslandsServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Parâmetros do protocolo
		List<String> paramNames = Arrays.asList("user_id",
				"user_longitude", "user_latitude", "distance");
		Map<String, String> params = new HashMap<String, String>();
		try {
			params = ParamUtil.getValues(request, paramNames);
		} catch (ParameterNotFoundException e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		Double longitude = null;
		Double latitude = null;
		Long user_id = null;
		Double distance = null;
		Point p = null;
		try {
			user_id = Long.parseLong(params.get("user_id"));
			longitude = Double.parseDouble(params.get("user_longitude"));
			latitude = Double.parseDouble(params.get("user_latitude"));
			distance = Double.parseDouble(params.get("distance"));
			p = PostGISUtil.getPoint(longitude, latitude);
		} catch (Exception e) {
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		} 
		IslandDAO dao = new IslandDAO(Island.class);
		List<Island> nearIslands = dao.findAllNear(p, distance);
		DAOUtil<Island> daoUtil = new DAOUtil<Island>();
		daoUtil.listDetached(nearIslands);
		PrintWriter pw = response.getWriter();
		pw.write(JSONUtil.toJSON(nearIslands));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
	}

}
